package cn.shyouchi.wuguanjia.android.ui.train;

import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.shyouchi.wuguanjia.android.Global;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.train.TrainApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class TrainPostActivity extends BaseActivity {


    TrainApi mTrainApi;
    TrainPostEntity mMasterEntity;
    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.tv_count)
    TextView mTvCount;
    @BindView(R.id.banner)
    BGABanner mBanner;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_pos)
    TextView mTvPos;
    @BindView(R.id.tv_content)
    TextView mTvContent;
    @BindView(R.id.tv_proi)
    TextView mTvProi;
    @BindView(R.id.tv_next)
    TextView mTvNext;
    @BindView(R.id.item_action)
    RelativeLayout mItemAction;


    boolean canLoad = true;

    int curPage = 0;
    int maxPage;


    @Override
    public int initContentView() {
        return R.layout.activity_train_post;
    }

    @Override
    public void initInjector() {
        mTrainApi = new TrainApi();
        curPage = getIntent().getIntExtra("curPage", 1);
        maxPage = getIntent().getIntExtra("maxPage", 1);


        LogUtil.e(String.format("cur = %s \n max = %s", curPage, maxPage));

    }

    @Override
    public void initUiAndListener() {


        ButterKnife.bind(this);
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        mTopBar.setTitle(getTitle().toString());
        setSupportActionBar(mTopBar.getToolbar());

        mBanner.setAutoPlayAble(false);

        mBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                mTvPos.setText(String.format("%s/%s", position + 1, mBanner.getItemCount()));
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        fetchMasterData(curPage);

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    private void fillData(TrainPostEntity entity) {
        mMasterEntity = entity;

        initBanner(entity.getImage());

        mTvPos.setText(String.format("%s/%s", 1, entity.getImage().size()));

        mTvTitle.setText(entity.getTrainingname());

        mTvContent.setText(entity.getTrainingcontent());


//        mBanner.setAdapter(new BGABanner.Adapter() {
//            @Override
//            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
//
//            }
//        });


//        mTvMasterAge.setText(entity.getAge() + "岁");
//        mTvMasterHeight.setText(String.valueOf(entity.getHeight()));
//        mTvMasterWork.setText(entity.getJob());
//        mTvMasterWorktime.setText(entity.getWorkinghours());
//        mTvMasterChepai.setText(entity.getNumberplates());
//        mTvMasterPhone.setText(entity.getPhone());
//        mTvMatserOther.setText(entity.getRemarks());
//        mTvMasterName.setText(String.format("%s/%s", entity.getName(), entity.getSex() == 1 ? "男" : "女"));
//        loadHead(Global.BASE_URL + entity.getImages(), mImgMasterHeader);

        if (!entity.isWhether()) {
            EventBus.getDefault().post(new DataChangeEvent());
            startCount();
        }

    }


    private void initBanner(List<TrainPostEntity.ImageBean> image) {

        List<String> modules = new ArrayList<>();
        List<String> tips = new ArrayList<>();

        for (TrainPostEntity.ImageBean imageBean : image) {
            modules.add(Global.BASE_URL + imageBean.getImage());
            tips.add("Banner 06");
        }


        mBanner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                Glide.with(mContext)
                        .load(model.toString())
                        .into((ImageView) view);
            }
        });
        mBanner.setData(modules, tips);
    }


    private void fetchMasterData(int page) {
        mTrainApi.getPostData(page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<BaseRequestResult<TrainPostEntity>>(mContext) {
                    @Override
                    public void onNext(BaseRequestResult<TrainPostEntity> result) {
                        fillData(result.getResultMessage());
                    }
                });
    }


    private Observable<Integer> countdown(int time) {
        if (time < 0) time = 0;
        final int countTime = time;
        return Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(new Func1<Long, Integer>() {
                    @Override
                    public Integer call(Long increaseTime) {
                        return countTime - increaseTime.intValue();
                    }
                })
                .take(countTime + 1);
    }


    private void startCount() {
        countdown(30)
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        canLoad = false;
                        mTvCount.setVisibility(View.VISIBLE);
                    }
                })
                .subscribe(new Subscriber<Integer>() {
                    @Override
                    public void onCompleted() {
                        canLoad = true;
                        mTvCount.setVisibility(View.INVISIBLE);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(Integer integer) {
                        mTvCount.setText(integer + "s");
                    }
                });
    }


    @OnClick({R.id.tv_proi, R.id.tv_next})
    public void onClick(View view) {


        if (canLoad) {
            switch (view.getId()) {
                case R.id.tv_proi:

                    if (curPage - 1 > 0) {
                        curPage--;
                        fetchMasterData(curPage);
                    } else {
                        ToastUtil.showToast("没有了");
                    }
                    break;
                case R.id.tv_next:
                    if (curPage + 1 <= maxPage) {
                        curPage++;
                        fetchMasterData(curPage);
                    } else {
                        ToastUtil.showToast("没有了");
                    }
                    break;
            }
        } else {
            ToastUtil.showToast(mTvCount.getText() + "后才能加载");
        }
    }
}
